using System.Text.Json;
using FytSoa.Application.Erp.Param;
using FytSoa.Domain.Erp;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Erp;

/// <summary>
/// erp-采购入库详细服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v9")]
public class ErpPurchaseOrderInfoService : IApplicationService 
{
    private readonly SugarRepository<ErpPurchaseOrderInfo> _thisRepository;
    public ErpPurchaseOrderInfoService(SugarRepository<ErpPurchaseOrderInfo> thisRepository)
    {
        _thisRepository = thisRepository;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ErpPurchaseOrderInfoDto>> GetPagesAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ErpPurchaseOrderInfoDto>>();
    }
    
    /// <summary>
    /// 根据采购查询采购订单商品信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpPurchaseOrderInfoDto>> GetListAsync(PageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(param.Id!=0,m=>m.OrderId==param.Id)
            .Includes(m=>m.Product)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();
        return query.Adapt<List<ErpPurchaseOrderInfoDto>>();
    }
    
    /// <summary>
    /// 根据采购查询采购订单商品信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<List<ErpProductOrderDto>> GetByOrderAsync(PurchaseOrderSearchParam param)
    {
        var product = await _thisRepository.GetListAsync(m => m.OrderId == param.Id);
        var productIds = product.Select(m => m.ProductId).ToList();
        var productRepository = _thisRepository.ChangeRepository<SugarRepository<ErpProduct>>();
        var query = await productRepository.AsQueryable()
            .WhereIF(string.IsNullOrEmpty(param.ProductIds),m=>productIds.Contains(m.Id))
            .WhereIF(!string.IsNullOrEmpty(param.ProductIds),m=>param.ProductIds.StrToListLong().Contains(m.Id))
            .WhereIF(!string.IsNullOrEmpty(param.TypeId),m=>m.TypeId==long.Parse(param.TypeId))
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Name.Contains(param.Key))
            .Includes(m=>m.Type)
            .Includes(m=>m.Unit)
            .Includes(m=>m.Employee)
            .Includes(m=>m.Supplier)
            .OrderByDescending(m=>m.Id)
            .ToListAsync();

        var returnProductList = new List<ErpPurchaseReturnInfo>();
        //处理退货逻辑
        if (param.Type==2)
        {
            //查询采购退货信息，采购数-退货数
            var retrunRepository = _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseReturn>>();
            var returnIds = await retrunRepository.AsQueryable().Where(m => m.OrderId == param.Id)
                .Select(m=>m.Id).ToListAsync();
            if (returnIds.Count>0)
            {
                var returnInfoRepository= _thisRepository.ChangeRepository<SugarRepository<ErpPurchaseReturnInfo>>();
                returnProductList = await returnInfoRepository.GetListAsync(m => returnIds.Contains(m.ReturnId));
            }
        }
        var result=query.Adapt<List<ErpProductOrderDto>>();
        foreach (var item in result)
        {
            var returnSum = 0;
            if (param.Type==2 && returnProductList.Count>0)
            {
                returnSum = returnProductList.Where(m => m.ProductId == item.Id)
                    .Sum(m => m.Count);
            }
            var model = product.FirstOrDefault(m => m.ProductId == item.Id);
            if (model!=null)
            {
                item.Count = model.Count-returnSum;
                item.IsInStock = model.IsInStock;
                item.Price = model.Amount;
            }
        }
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ErpPurchaseOrderInfoDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ErpPurchaseOrderInfoDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(List<ErpPurchaseOrderInfoDto> model)
    {
        var orderId = model.FirstOrDefault().OrderId;
        await _thisRepository.DeleteAsync(m => m.OrderId == orderId);
        await _thisRepository.InsertRangeAsync(model.Adapt<List<ErpPurchaseOrderInfo>>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ErpPurchaseOrderInfoDto model) =>
        await _thisRepository.UpdateAsync(model.Adapt<ErpPurchaseOrderInfo>());

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
